package com.douyin.controller;

import com.douyin.aspect.ClientLogin;
import com.douyin.common.constants.PathConstant;
import com.douyin.common.dto.UserLoginDTO;
import com.douyin.common.vo.BaseResponseVO;
import com.douyin.common.vo.FeedResponseVO;
import com.douyin.common.vo.VideoVO;
import com.douyin.entity.Video;
import com.douyin.exception.CommonException;
import com.douyin.manager.VideoManager;
import com.douyin.service.UserService;
import com.douyin.service.VideoService;
import com.douyin.utils.AliOSSUtils;
import com.douyin.utils.DateUtils;
import com.douyin.utils.TokenUtils;
import com.douyin.utils.VideoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Author:WJ
 * Date:2023/2/18 13:07
 * Description:<视频相关接口>
 */
@Slf4j
@RestController
public class VideoController {

    @Autowired
    private VideoManager videoManager;

    @Autowired
    private VideoService videoService;

    @Autowired
    private UserService userService;

    /**
     * 获取视频流
     *
     * @param latestTime
     * @param token
     * @return
     * @throws ParseException
     */
    @GetMapping("/feed")
    public FeedResponseVO feed(@RequestParam(value = "latest_time", required = false) Long latestTime,
            @RequestParam(value = "token", required = false) String token) throws ParseException {
        Long userId = null;
        if (token != null) {
            if (!TokenUtils.verify(token)) {
                throw new CommonException("用户登录信息不正确");
            }
            userId = TokenUtils.getLoginUserDTO(token).getId();
            System.out.println(userId);
        }
        List<VideoVO> videoVOList = videoManager.getVideoVOList(latestTime, userId);
        log.info("获取视频流成功！");
        Long nextTime = DateUtils.curTimeMillis();
        if (!videoVOList.isEmpty()) {
            VideoVO lastVideoVO = videoVOList.get(videoVOList.size() - 1);
            Date date = videoService.getById(lastVideoVO.getId()).getCreatedTime();
            log.info("最后一个视频的时间为：{}", date);
            nextTime = DateUtils.getDate2Long(date);
        }
        return FeedResponseVO.success(videoVOList, nextTime);
    }

    /**
     * 获取用户视频列表
     *
     * @param userId
     * @param token
     * @param userLoginDTO
     * @return
     */
    @ClientLogin
    @GetMapping("/publish/list/")
    public FeedResponseVO getPublishList(@RequestParam("user_id") Long userId, @RequestParam("token") String token,
            UserLoginDTO userLoginDTO) {
        List<VideoVO> videoVOList = videoManager.getVideoVOByUserId(userId, userLoginDTO.getId());
        log.info("获取用户视频成功");
        return FeedResponseVO.success(videoVOList, null);
    }


    /**
     * 发表视频
     *
     * @param video
     * @param token
     * @param title
     * @param userLoginDTO
     * @return
     */
    @ClientLogin
    @PostMapping("/publish/action/")

    public BaseResponseVO uploadVideo(
            @RequestParam("data") MultipartFile video,
            @RequestParam("token") String token,
            @RequestParam("title") String title,
            UserLoginDTO userLoginDTO) {

        // 确保目录存在
        File videoDir = new File(PathConstant.videoSavePath);
        if (!videoDir.exists()) videoDir.mkdirs();

        File coverDir = new File(PathConstant.coverSavePath);
        if (!coverDir.exists()) coverDir.mkdirs();

        // 生成唯一文件名（避免覆盖）
        String originalName = video.getOriginalFilename();
        String extension = originalName.substring(originalName.lastIndexOf("."));
        String videoFileName = UUID.randomUUID() + extension;
        String coverFileName = videoFileName.replace(extension, "Cover.jpg");

        // 保存视频到本地
        File videoFile = new File(videoDir, videoFileName);
        try {
            video.transferTo(videoFile);
        } catch (IOException e) {
            throw new CommonException("上传视频失败: " + e.getMessage());
        }

        // 生成视频访问URL
        String videoUrl = PathConstant.videoBaseUrl + videoFileName;

        // 保存封面到本地
        String coverPath = PathConstant.coverSavePath + coverFileName;
        try {
            VideoUtils.fetchPic(videoFile, coverPath);
        } catch (Exception e) {
            throw new CommonException("上传视频封面失败: " + e.getMessage());
        }

        // 生成封面访问URL
        String coverUrl = PathConstant.coverBaseUrl + coverFileName;

        // 保存视频信息到数据库
        Video videoEntity = new Video();
        videoEntity.setAuthorId(userLoginDTO.getId());
        videoEntity.setCoverUrl(coverUrl);
        videoEntity.setPlayUrl(videoUrl);
        videoEntity.setTitle(title);
        videoService.save(videoEntity);

        userService.updateWorkCountById(1, userLoginDTO.getId());
        return BaseResponseVO.success();
    }

    /**
     * 删除视频
     *
     * @param videoId 视频ID
     * @param token 用户Token
     * @param userLoginDTO 当前登录用户
     * @return
     */
    @ClientLogin
    @DeleteMapping("/publish/delete/")
    public BaseResponseVO deleteVideo(@RequestParam("video_id") Long videoId,
                                      @RequestParam("token") String token,
                                      UserLoginDTO userLoginDTO) {
        // 获取视频信息
        Video video = videoService.getById(videoId);
        if (video == null) {
            throw new CommonException("视频不存在");
        }

        // 检查视频归属
        if (!video.getAuthorId().equals(userLoginDTO.getId())) {
            throw new CommonException("无权限删除该视频");
        }

        // 删除本地视频文件和封面
//        try {
//            String videoFilePath = PathConstant.videoSavePath + video.getPlayUrl().substring(PathConstant.videoBaseUrl.length());
//            String coverFilePath = PathConstant.coverSavePath + video.getCoverUrl().substring(PathConstant.coverBaseUrl.length());
//
//            File videoFile = new File(videoFilePath);
//            if (videoFile.exists()) videoFile.delete();
//
//            File coverFile = new File(coverFilePath);
//            if (coverFile.exists()) coverFile.delete();
//        } catch (Exception e) {
//            log.warn("删除本地视频文件或封面失败: {}", e.getMessage());
//        }

        // 删除数据库记录
        videoService.removeById(videoId);

        // 更新用户作品数量
        userService.updateWorkCountById(-1, userLoginDTO.getId());

        log.info("视频删除成功: {}", videoId);
        return BaseResponseVO.success();

    }
}
